package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;

import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable, OnReceiverListener {

    public ListView<String> chatList;
    public TextField inputField;
    private SocketServerManager manager;
    private ObservableList<String> chats = FXCollections.observableArrayList();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        manager = new SocketServerManager();
        manager.setOnReceiveTextListener(this);
        manager.start();
        chatList.setItems(chats);
    }

    @Override
    public void onReceive(String text) {
        System.out.println("读取到数据:" + text);
        chats.add(text);
    }

    @FXML
    public void onKeyPressed(KeyEvent event) {
        switch (event.getCode()) {
            case ENTER:
                String text = inputField.getText();
                chats.add("me:" + text);
                manager.sendText(text);
                inputField.setText("");
                event.consume();
                break;
        }
    }
}
